package com.lb.uts.service.policy;


import com.lb.uts.constants.LogConstants;
import com.lb.uts.entity.ScheduleJob;
import com.lb.uts.util.LotteryUtil;
import com.lb.uts.entity.CacheClient;
import com.lb.uts.util.PolicyUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

import static com.lb.uts.util.PolicyUtil.JOB_IP_LIST_CHANGING;

/**
 * 根据权重，返回一个执行器
 *
 * @author liangb
 * @version 3.0
 * @date 2019/4/28 11:58
 */
@Service
public class WeightSchedulingPolicy implements ISchedulingPolicy<CacheClient> {

    private static final Logger logger = LoggerFactory.getLogger(WeightSchedulingPolicy.class);

    @Override
    public CacheClient getSuitActiveClient(ScheduleJob job) {
        String systemName = job.getSystemName();
        while (true) {
            if (!JOB_IP_LIST_CHANGING) {
                List<CacheClient> jobIps = PolicyUtil.JOB_IP_LIST.get(systemName);
                if (CollectionUtils.isEmpty(jobIps)) {
                    logger.info(LogConstants.RANDOM_SCHEDULING_POLICY + "没有合适的执行器");
                    return null;
                }
                //得到执行器的权重
                int weightSum = 0;
                for (CacheClient cacheClient : jobIps) {
                    weightSum += cacheClient.getWeight();
                }
                //计算各自的权重ScheduleJobMapper
                //得到概率
                List<Double> orignalRates = new ArrayList<Double>();
                for (CacheClient cacheClient : jobIps) {
                    orignalRates.add(cacheClient.getWeight() * (1.0) / weightSum);
                }
                int winPrizeIndex = LotteryUtil.lottery(orignalRates);
                if (winPrizeIndex != -1) {
                    return jobIps.get(winPrizeIndex);
                }
                return null;
            } else {
                //此时后台线程正在刷新内存，等待，继续尝试
                logger.info(LogConstants.RANDOM_SCHEDULING_POLICY + "后台线程正在更新ip list，等待");
            }
        }
    }
}
